//
//  WMLoginViewController.swift
//  deWaterMarkingProject
//
//  Created by admin on 2025/9/9.
//

import UIKit
import AuthenticationServices

class WMLoginViewController: WMBaseViewController {
    
    @IBOutlet weak var mobilePhoneTxt: UITextField!
    @IBOutlet weak var smsCodeTxt: UITextField!
    @IBOutlet weak var sendSmsLabel: UILabel!
    
    @IBOutlet weak var checkBtn: UIButton!
    @IBOutlet weak var wechatBtn: UIButton!
    @IBOutlet weak var appleBtn: UIButton!
    
    var gcdTimer: DispatchSourceTimer?
    var cutTime: Int = 60
    var model = NTESQuickLoginModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        isNavigationBarHidden = true
        wechatBtn.isHidden = !WXApi.isWXAppInstalled()
        
        NotificationCenter.default.addObserver(forName: NSNotification.Name("WeChatLoginResponse"), object: nil, queue: OperationQueue.main) { [weak self] nt in
            if let code = nt.userInfo?["code"] as? String,let state = nt.userInfo?["state"] as? String {
                self?.requestWechatLogin(code, state:state)
            }
        }
        
        customUI()
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(actionTap))
        view.addGestureRecognizer(tap)
        
        let closeBtn = UIButton()
        closeBtn.setImage(UIImage(named: "delete_icon"), for: .normal)
        closeBtn.addTarget(self, action: #selector(actionBack), for: .touchUpInside)
        view.addSubview(closeBtn)
        closeBtn.snp.makeConstraints { make in
            make.width.height.equalTo(40)
            make.top.equalTo(statusBarHeight)
            make.right.equalTo(-10)
        }
        
        Async.main(after: 0.5) { [weak self] in
            self?.authorizeLogin()
        }
    }

    @objc
    func actionBack() {
        navigationController?.popViewController(animated: true)
        
    }

    @objc
    func actionTap() {
        view.endEditing(true)
    }
    
    @objc
    func actionClose() {
        dismiss(animated: true)
    }
    
    func getCodeSuccess() {
        cutTime = 60
        beginCutTime()
    }
    
    func beginCutTime() {
        gcdTimer = DispatchSource.makeTimerSource()
        gcdTimer!.schedule(wallDeadline: DispatchWallTime.now(), repeating: DispatchTimeInterval.seconds(1), leeway: DispatchTimeInterval.seconds(0))
        gcdTimer!.setEventHandler { [weak self] in
            guard let self = self else { return }
            if self.cutTime <= 0 {
                self.gcdTimer!.cancel()
                self.gcdTimer = nil
                Async.main {
                    self.sendSmsLabel.text = "重新获取"
                }
            }else {
                Async.main {
                    self.sendSmsLabel.text = "\(self.cutTime)s"
                    self.cutTime -= 1
                }
            }
        }
        gcdTimer!.resume()
    }
    
    func loginSuccess(_ data: [String: Any]) {
        UserDefaults.standard.setValue(data["userId"] ?? 0, forKey: UserDefaultsKey.loginUserId)
        UserDefaults.standard.setValue(data["token"] ?? "", forKey: UserDefaultsKey.loginUserToken)
        UserDefaults.standard.setValue(data["userName"] ?? "", forKey: UserDefaultsKey.loginUserName)
        UserDefaults.standard.setValue(data["headImage"] ?? "", forKey: UserDefaultsKey.loginUserAvatar)
        navigationController?.popViewController()
    }
    
    //获取验证码
    func requestCode() {
        WMAgentApi.shared.requestApi(ApiEnum.verifyCode(mobilePhoneTxt.text.or(""))) { res in
            let code: String = res["code"] as! String
            if (code == "200" || code == "0"){
                Async.main {
                    self.getCodeSuccess()
                }
            }
            
        }
        
    }
    
    //微信登录
    func requestWechatLogin(_ code: String, state: String) {
        showHUD()
        WMAgentApi.shared.requestApi(ApiEnum.wechatLogic(code)) { res in
            let code: String = res["code"] as! String
            guard let data = res["data"] as? [String: Any] else { return }
            Async.main {
                self.hideHUD()
            }
            if (code == "200" || code == "0") {
                self.loginSuccess(data)
            }
        }
    }
    
    //苹果登录
    func requestAppleLogin(_ token: String, _ userId: String) {
        showHUD()
        WMAgentApi.shared.requestApi(ApiEnum.appleLogic(token, userId)) { res in
            let code: String = res["code"] as! String
            guard let data = res["data"] as? [String: Any] else { return }
            Async.main {
                self.hideHUD()
            }
            if (code == "200" || code == "0") {
                self.loginSuccess(data)
            }
        }
    }
    
    //手机号验证码登录
    func requestPhoneLogin() {
        showHUD()
        WMAgentApi.shared.requestApi(ApiEnum.phoneLogin(mobilePhoneTxt.text.or(""), smsCodeTxt.text.or(""))) { res in
            let code: String = res["code"] as! String
            guard let data = res["data"] as? [String: Any] else { return }
            Async.main {
                self.hideHUD()
            }
            if (code == "200" || code == "0") {
                self.loginSuccess(data)
            }else{
                let message = res["message"] as? String
                KBToast.show(message ?? "")
            }
        }
    }
    
    //一键登录
    func requestOneKeyPhoneLogin(_ token: String, _ accessToken: String) {
        WMAgentApi.shared.requestApi(ApiEnum.oneclickLogin(token, accessToken)) { res in
            let code: String = res["code"] as! String
            guard let data = res["data"] as? [String: Any] else { return }
            Async.main {
                self.hideHUD()
            }
            if (code == "200" || code == "0") {
                self.loginSuccess(data)
            }
        }
    }
    //发送验证码
    @IBAction func sendSmsBtnClickAction(_ sender: Any) {
        view.endEditing(true)
        if mobilePhoneTxt.text.or("").isEmpty {
            showTips("请输入手机号")
            return
        }
        requestCode()
    }
    //是否同意协议
    @IBAction func checkBtnClickAction(_ sender: Any) {
        checkBtn.isSelected = !checkBtn.isSelected
    }
    //用户协议
    @IBAction func userProtocolBtnClickAction(_ sender: Any) {
        let web = WebViewController()
        web.modalPresentationStyle = .fullScreen
        web.url = UserDefaults.standard.value(forKey: UserDefaultsKey.userProtocol) as? String ?? ""
        present(web, animated: true)
    }
    //隐私政策
    @IBAction func pricyProtocolBtnClickAction(_ sender: Any) {
        let web = WebViewController()
        web.url = UserDefaults.standard.value(forKey: UserDefaultsKey.sercurityProtocol) as? String ?? ""
        web.modalPresentationStyle = .fullScreen
        present(web, animated: true)
    }
    //微信登录
    @IBAction func wechatBtnClickAction(_ sender: Any) {
        view.endEditing(true)
        if !checkBtn.isSelected {
//            showTips("请阅读并同意《隐私政策》及《用户协议》")
            LoginProtocolAlertView.show() { [weak self] index in
                if index == 1 {
                    self?.checkBtn.isSelected = true
                    let req = SendAuthReq()
                    req.scope = "snsapi_userinfo,snsapi_base"
                    req.state = "wx_oauth_authorization_state"
                    WXApi.send(req) { e in
                        print(e)
                    }
                }
            }
            return
        }
        let req = SendAuthReq()
        req.scope = "snsapi_userinfo,snsapi_base"
        req.state = "wx_oauth_authorization_state"
        WXApi.send(req) { e in
            print(e)
        }
    }
    //苹果登录
    @IBAction func appleBtnClickAction(_ sender: Any) {
        view.endEditing(true)
        if !checkBtn.isSelected {
//            showTips("请阅读并同意《隐私政策》及《用户协议》")
            LoginProtocolAlertView.show() { [weak self] index in
                if index == 1 {
                    self?.checkBtn.isSelected = true
                    self?.appleLogin()
                }
            }
            return
        }
        appleLogin()
    }
    
    func appleLogin() {
        guard #available(iOS 13.0, *) else {
            return
        }
        let appleIDRequest = ASAuthorizationAppleIDProvider().createRequest()
        let controller = ASAuthorizationController(authorizationRequests: [appleIDRequest])
        controller.delegate = self
        controller.presentationContextProvider = self
        controller.performRequests()
    }
    
    //确定按钮点击事件
    @IBAction func loginBtnClickAction(_ sender: Any) {
        view.endEditing(true)
        if mobilePhoneTxt.text.or("").isEmpty {
            showTips("请输入手机号")
            return
        }
        if smsCodeTxt.text.or("").isEmpty {
            showTips("请输入验证码")
            return
        }
        if !checkBtn.isSelected {
//            showTips("请阅读并同意《隐私政策》及《用户协议》")
            LoginProtocolAlertView.show() { [weak self] index in
                if index == 1 {
                    self?.checkBtn.isSelected = true
                    self?.requestPhoneLogin()
                }
            }
            return
        }
        requestPhoneLogin()
    }
    
    lazy var closeBtn: UIButton = {
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 44))
        btn.setImage(UIImage(named: "delete_icon"), for: .normal)
        btn.addTarget(self, action: #selector(actionClose), for: .touchUpInside)
        
        return btn
    }()
    
}

extension WMLoginViewController {
    
    @objc
    func actionOther() {
        NTESQuickLoginManager.sharedInstance().closeAuthController()
    }
    
    func customUI() {
        model.currentVC = self
        model.presentDirectionType = .present
        model.navBgColor = .white
        model.authWindowPop = .fullScreen
        model.backgroundColor = UIColor.white
        model.shouldHiddenNavReturnImg = false
        model.navText = ""
        model.navReturnImg = UIImage(named: "delete_icon")!
        model.navReturnImgLeftMargin = kScreenWidth - 44 - 10

        /// logo
        model.logoImg = UIImage(named: "app_icon.png")!
        model.logoWidth = 52
        model.logoHeight = 52
        model.logoHidden = false
        model.logoOffsetTopY = 80

        /// 手机号码
        model.numberFont = UIFont.systemFont(ofSize: 18, weight: .medium)
        model.numberOffsetTopY = 160
        model.numberHeight = 27
        model.numberFont = UIFont.systemFont(ofSize: 20, weight: .medium)

        ///  品牌
        model.brandFont = UIFont.systemFont(ofSize: 12)
        model.brandWidth = 200
        model.brandBackgroundColor = .clear
        model.brandHeight = 20
        model.brandOffsetTopY = 200
        model.brandColor = UIColor(valueRGB: 0xAEADAB, alpha: 1.0)

        /// 登录按钮
        model.logBtnTextFont = UIFont.systemFont(ofSize: 14)
        model.logBtnTextColor = UIColor.white
        model.logBtnText = "一键登录"
        model.logBtnRadius = 8
        model.logBtnHeight = 52
        model.logBtnWidth = kScreenWidth - 60
        model.logBtnUsableBGColor = UIColor(valueRGB: UInt(OEMInfo.themeHex), alpha: 1.0)
        model.logBtnOffsetTopY = 260

        /// 隐私协议
        model.appPrivacyText = "我已阅读并同意《默认》和《隐私协议》、《用户协议》"
        model.appFPrivacyText = "《隐私协议》"
        model.appPrivacyOriginBottomMargin = 50
        model.appFPrivacyURL = UserDefaults.standard.value(forKey: UserDefaultsKey.userProtocol) as? String ?? ""
        model.appSPrivacyText = "《用户协议》"
        model.appFPrivacyURL = UserDefaults.standard.value(forKey: UserDefaultsKey.sercurityProtocol) as? String ?? ""
        model.privacyColor = UIColor(valueRGB: 0xAEADAB, alpha: 1.0)
        model.protocolColor = UIColor(valueRGB: UInt(OEMInfo.themeHex), alpha: 1.0)
        model.uncheckedImg = UIImage(named: "select_n")!
        model.checkedImg = UIImage(named: "select_s")!
        model.checkboxWH = 24
        model.privacyState = false
        model.isOpenSwipeGesture = false
        model.privacyFont = UIFont.systemFont(ofSize: 14)

//        model.prograssHUDBlock = { [weak self] customView in
//            if let customView = customView {
//                let view = LoginProtocolAlertView()
//                view.show(inView: customView)
//                view.clickBlock = { index in
//                    if index == 1 {
//                        self?.model.privacyState = true
//                    }
//                }
////                customView.addSubview(view)
////                view.snp.makeConstraints { make in
////                    make.center.equalToSuperview()
////                }
//            }
//        }
        
        model.customViewBlock = { [weak self] customView in
            if let self = self, let customView = customView {
                let otherBtn = UIButton()
                otherBtn.backgroundColor = UIColor(valueRGB: 0xF4F4FA, alpha: 1.0)
                otherBtn.layer.cornerRadius = 8
                otherBtn.setTitle("使用其他手机号", for: .normal)
                otherBtn.setTitleColor(UIColor.black, for: .normal)
                otherBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
                customView.addSubview(otherBtn)
                otherBtn.snp.makeConstraints { make in
                    make.centerX.equalToSuperview()
                    make.top.equalTo(customView).offset(328)
                    make.height.equalTo(52)
                    make.left.equalTo(30)
                }
                otherBtn.addTarget(self, action: #selector(self.actionOther), for: .touchUpInside)
                
                let tipsLabel = UILabel()
                tipsLabel.text = "未注册手机号验证后将自动注册"
                tipsLabel.textColor = UIColor(valueRGB: 0xAEADAB, alpha: 1.0)
                tipsLabel.font = UIFont.systemFont(ofSize: 12)
                customView.addSubview(tipsLabel)
                tipsLabel.snp.makeConstraints { make in
                    make.centerX.equalToSuperview()
                    make.top.equalTo(otherBtn.snp.bottom).offset(40)
                }
            }
        };

        /**登录按钮点击事件回调*/
        model.loginActionBlock = { [weak self] privacyType in
            if privacyType {
                NTESQuickLoginManager.sharedInstance().closeAuthController()
                self?.showHUD()
            }
        };
                
        /**协议点击事件回调*/
        model.privacyActionBlock = { [weak self] privacyType in
            if (privacyType == 0) {
                //点击默认协议
                // 移动
                var url = "https://wap.cmpassport.com/resources/html/contract.html"
                let code = UserDefaults.standard.value(forKey: UserDefaultsKey.oneKeyPhoneCodeKey) as? String ?? ""
                if code == "0" {
                    // 电信
                    url = "https://e.189.cn/sdk/agreement/detail.do?hidetop=true"
                }else if code == "100" {
                    // 联通
                    url = "https://ms.zzx9.cn/html/oauth/protocol2.html"
                }
                let web = WebViewController()
                web.modalPresentationStyle = .fullScreen
                web.url = url
                self?.present(web, animated: true)
            }else if (privacyType == 1) {
                // 点击自定义第1个协议;
                let web = WebViewController()
                web.modalPresentationStyle = .fullScreen
                web.url = UserDefaults.standard.value(forKey: UserDefaultsKey.sercurityProtocol) as? String ?? ""
                self?.present(web, animated: true)
            }else if (privacyType == 2) {
                // 点击自定义第1个协议;
                let web = WebViewController()
                web.modalPresentationStyle = .fullScreen
                web.url = UserDefaults.standard.value(forKey: UserDefaultsKey.userProtocol) as? String ?? ""
                self?.present(web, animated: true)
            }
        };

        NTESQuickLoginManager.sharedInstance().setupModel(model)
    }
    
    func authorizeLogin() {
        NTESQuickLoginManager.sharedInstance().cucmctAuthorizeLoginCompletion { res in
            let accessToken = res["accessToken"] as? String ?? ""
            let token = UserDefaults.standard.value(forKey: UserDefaultsKey.oneKeyPhoneTokenKey) as? String ?? ""
            if !accessToken.isEmpty {
                Async.main(after: 0.5) { [weak self] in
                    self?.requestOneKeyPhoneLogin(token, accessToken)
                }
            }
        }
    }

}

@available(iOS 13.0, *)
extension WMLoginViewController: ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
    public func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        UIApplication.shared.delegate!.window!!
    }
    
    public func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        if let credential = authorization.credential as? ASAuthorizationAppleIDCredential, let token = credential.identityToken, let tokenStr = String.init(data: token, encoding: .utf8) {
            requestAppleLogin(tokenStr, credential.user)
        }
    }
    
    public func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        switch (error) {
        case ASAuthorizationError.canceled:
            break;
        default:
            print("授权失败，请您稍后再试")
            break;
        }
    }
}
